import 'dart:async';
import 'dart:isolate';
import 'dart:io';
import 'dart:convert';


//https://dart.cn/language/concurrency/#the-async-await-syntax
const String filename = 'with_keys.json';
Future<void> main() async {
  print('Start');
  await fetchData();
  print('End');

  final receivePort = ReceivePort();

  await Isolate.spawn(isolateFunction, receivePort.sendPort);

  receivePort.listen((message) {
    print('Received: $message');
    receivePort.close();
  });


  print('Start reading file...');

  try {
    String content = await _readFileAsync();
    print('File content: $content');
  } catch (e) {
    print('Error reading file: $e');
  }

  print('End of program.');


// 读取数据。
  final fileData = await _readFileAsync();
  final jsonData = jsonDecode(fileData);

  // 使用该数据。
  print('Number of JSON keys: ${jsonData.length}');


//https://dart.cn/language/concurrency/#streams
// 创建一个每秒发出一个值的 Stream
  Stream<int> stream = Stream.periodic(const Duration(seconds: 1), (i) => i * i);

  // 监听 Stream 并打印每个值
  StreamSubscription<int> subscription = stream.listen((value) {
    print('Emitted value: $value');
  });

  // 5 秒后取消订阅
  Future.delayed(Duration(seconds: 5), () {
    subscription.cancel();
    print('Stream subscription canceled.');
  });

// 创建一个示例 Stream
  final numbers = Stream.fromIterable([1, 2, 3, 4, 5]);

  // 计算累积和
  final sumStreamResult = sumStream(numbers);

  // 监听并打印结果
  await for (final sum in sumStreamResult) {
    print('Cumulative sum: $sum');
  }


print('Start');
  await fib40();
  print('End');




//https://dart.cn/language/concurrency/#the-main-isolate/#the-isolate-life-cycle/#event-handling
 print('Main function started');

  // 模拟异步操作
  Future.delayed(Duration(seconds: 1), () {
    print('Async operation completed');
  });

  // 注册事件监听器
  Timer.periodic(Duration(seconds: 2), (timer) {
    print('Periodic event triggered');
  });

  // 模拟长时间运行的同步操作
  for (int i = 0; i < 1000000000; i++) {
    // 这里可以添加一些计算
  }

  print('Main function exiting');



























}






//https://dart.cn/language/concurrency/#asynchronous-programming
Future<String> _readFileAsync() async {
  final file = File(filename);
  final contents = await file.readAsString();
  return contents.trim();
}



//https://dart.cn/language/concurrency/#event-loop
Future<void> fetchData() async {
  print('Fetching data...');
  await Future.delayed(Duration(seconds: 2)); // 模拟网络请求
  print('Data fetched!');
}

void isolateFunction(SendPort sendPort) {
  sendPort.send('Hello from isolate!');
}



//https://dart.cn/language/concurrency/#await-for-and-yield
Stream<int> sumStream(Stream<int> stream) async* {
  var sum = 0;
  await for (final value in stream) {
    sum += value;
    yield sum;
  }
}


//https://dart.cn/language/concurrency/#using-isolates
int slowFib(int n) => n <= 1 ? 1 : slowFib(n - 1) + slowFib(n - 2);

Future<int> fib40() async {
  var result = await Isolate.run(() => slowFib(40));
  print('Fib(40) = $result');
  return result;
  }

